/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settings; 

import com.hisense.settings.PowerOnSettings;
import com.hisense.settings.util.PowerDataGettings;
import com.hisense.settings.util.Wrapper;
import android.content.DialogInterface.OnDismissListener;

import static com.google.android.tv.settings.TvSettings.System.SCREEN_DIM_TIMEOUT;
import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
import static android.provider.Settings.System.SOUND_EFFECTS_ENABLED;
/*import com.marvell.tv.TVAVSettingsConstants.TvSourceType;
import com.marvell.willowtv.framework.features.TvFramework;
import com.marvell.willowtv.framework.util.atsc.InputSourceType;
import com.marvell.willowtv.framework.features.Picture;
import com.marvell.willowtv.framework.model.atsc.USDTVInputVideoResolution;
import com.marvell.willowtv.framework.util.atsc.Events;
import com.marvell.willowtv.framework.model.avsettings.VideoInfoUpdate;*/

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.ActivityManagerNative;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.hardware.display.DisplayManager;
import android.hardware.display.WifiDisplay;
import android.hardware.display.WifiDisplayStatus;
import android.os.Bundle;
import android.os.RemoteException;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;

import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.KeyEvent;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import com.android.settings.R;
import com.hisense.settings.util.HisUtils;
import com.android.internal.view.RotationPolicy;
import com.android.settings.DreamSettings;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.SystemProperties;
/**
 * VideoOut is used for box tv changed to others
 * @author libaocheng
 */

public class DisplaySettings extends SettingsPreferenceFragment implements
        Preference.OnPreferenceChangeListener, OnPreferenceClickListener {
    private static final String TAG = "DisplaySettings";
	private boolean click_ok=false;
	private boolean dialog_dismiss=false;
    public static final String KEY_IMAGE_MODE = "image_mode";
	private static final String KEY_ASPECTRATIO_MODE = "aspectratio";
	private static final String KEY_COLORTEMPERATURE_MODE = "image_colortemperature";
	public static final String KEY_DYNAMICNOISEREDUCTION_MODE = "image_dynamicnoisereduction";	
    private static final String KEY_IMAGE_BRIGHTNESS = "image_brightness";
	private static final String KEY_IMAGE_CONTRAST = "image_contrast";
	private static final String KEY_IMAGE_COLOR = "image_color";
	private static final String KEY_IMAGE_TINT = "image_tint";
	private static final String KEY_IMAGE_SHARPNESS = "image_sharpness";
	private static final String KEY_IMAGE_BACKLIGHT = "image_backlight";
	private static final String KEY_SCREEN_ADJUST = "image_screen";
	private static final String KEY_IMAGE_RESET = "image_reset";
	private static final int DIALOG_IMAGE_RESET = 123;
	private static final int COLORTEMPERATURE_MODE_NORMAL = 0;
	private static final int COLORTEMPERATURE_MODE_WARM = 2;
	private static final int COLORTEMPERATURE_MODE_COOL = 1;

	private static final int DYNAMICNOISE_MODE_OFF = 0;
	private static final int DYNAMICNOISE_MODE_LOW = 1;
	private static final int DYNAMICNOISE_MODE_MEDIUM = 2;
	private static final int DYNAMICNOISE_MODE_HIGH = 3;

	private static final int IMAGE_MODE_RESET_VALUE = 0;
	private static final int IMAGE_MODE_STANDARD = 0;
	private static final int IMAGE_MODE_VIVID = 1;
	private static final int IMAGE_MODE_GAME = 4;
	private static final int IMAGE_MODE_THEATER = 3;
	private static final int IMAGE_MODE_ENERGYSAVING = 6;
	private static final int IMAGE_MODE_CUSTOM = 7;
	
	private static final int ASPECTRATIO_MODE_RESET_VALUE = 1;
	private static final int COLORTEMPERATURE_MODE_RESET_VALUE = 0;
	private static final int DYNAMICNOISEREDUCTION_MODE_RESET_VALUE = 1;
	private static final int VALUE_DYNAMIC = 1;
	private static final int VALUE_DYNAMIC_BACKLIGHT = 1;

	public static String RETAILMODE_IMAGEMODE = "retailmode_old_imagemode";
	public static String RETAILMODE_DYNAMICNOISEMODE = "retailmode_old_dynamicnoismode";
	public static String RETAILMODE_DYNAMICBACKLIGHT = "retailmode_old_dynamicbacklight";
	public static String RETAILMODE_DYNAMICCONTRAST = "retailmode_old_dynamiccontrast";
	public static String RETAILMODE_HASSAVE = "retailmode_old_dynamiccontrast";

	public static String CUSTOM_MODE_COLORTEMPERETURE = "custom_mode_colortemperature_mode";
	public static String CUSTOM_MODE_DYNAMICNOISE = "custom_mode_dynamicnoise_mode";
	//dynamic ontrast setting
	private static final String KEY_DYNAMIC_CONTRAST = "dynamic_contrast";
	private static final int VALUE_DYNAMIC_CONTRAST_ON = 1;
	private static final int VALUE_DYNAMIC_CONTRAST_OFF = 0;	
	//overscan
	private static final String KEY_IMAGE_OVERSCAN = "image_overscan";
	private static final int VALUE_IMAGE_OVERSCAN_ON = 1;
	private static final int VALUE_IMAGE_OVERSCAN_OFF = 0;
	private static final String EVENTS_CHANGE = "com.marvell.usdtv.app.listener.USDTV_EVENT";
	public static final String EXTRA_USDTV_EVENT = "Events";
	private Context mContext = null;
	//dynamic backlight
	private static final String KEY_DYNAMIC_BACKLIGHT = "dynamic_backlight";
	private static final int VALUE_DYNAMIC_BACKLIGHT_ON = 1;
	private static final int VALUE_DYNAMIC_BACKLIGHT_OFF = 0;

	//Frequence 120
	private static final String KEY_FREQUENCE120_MODE = "image_frequence120";
  
	//add for sync with ToolSetting->Aspectrario
	public static final String ASPECT_RATIO_ENABLE = "Aspectratio_enable";

	private static int mOldAspectratioMode;
	private static int mOldImageMode;
	private static int mOldNoiseMode;
	private static int mOldColorTemMode;
	private static int mOldBrightness;
	private static int mOldContrast;
	private static int mOldColor;
	private static int mOldTint;
	private static int mOldSharpness;
	private static int mOldBacklight;
	private static int mOldColortemperature;
	private static int mOld120HzEffect;
	
	
    private ListPreference mImageModePreference;
	private ListPreference mAspectratioPreference;
	private Preference mBrightnessPreferrence;
//	private SeekBarPreference mContrastPreferrence;
	private Preference mContrastPreferrence;
	private Preference mColorPreferrence;
	private Preference mTintPreferrence;
	private Preference mSharpnessPreferrence;	
	private Preference mBacklightPreference;
	private ListPreference mColortemperaturePreference;
	private ListPreference mDynamicNoiseReductionPreference;
	private ListPreference mFrequence120Preference;
	private PreferenceScreen mScreenVGAAdjust;
	private PreferenceScreen mImageResetpPreference;
	private CheckBoxPreference checkboxOverscan;
	private CheckBoxPreference checkboxBacklight;
	private CheckBoxPreference checkboxContrast;

    private OnItemSelectedListener mItemSelectedListener = null;
    private Preference mCurrentPreference = null;
    private AlertDialog mAlertDialog = null;
    private DialogInterface.OnCancelListener mOnCancelListener= null; 

    private View.OnClickListener mOnClickListener = null; 

	
	private SharedPreferences mSharedPrefs;
	SharedPreferences.Editor editor;
	private PowerDataGettings mPdg;

	private static AlertDialog        localDialog = null;
	private static final String RO_HARDWARE = "50K611GWUS";
	private String Machine = SystemProperties.get("ro.hardware", " ");
	
	private static final int FALLBACK_SCREEN_TIMEOUT_VALUE = 30000;

    private static final String KEY_SCREEN_TIMEOUT = "screen_timeout";
    private static final String KEY_ACCELEROMETER = "accelerometer";
    private static final String KEY_FONT_SIZE = "font_size";
    private static final String KEY_NOTIFICATION_PULSE = "notification_pulse";
    private static final String KEY_SCREEN_SAVER = "screensaver";
    private static final String KEY_WIFI_DISPLAY = "wifi_display";
    /*
     * this is used for picture Deep color
     */
    private static final String KEY_DEEP_COLOR_MODE = "deep_color";
    private static final String DEEP_COLOR_MODE_8BIT = "8bit";
    //private VideoOutput mVideoOut;

    private static final int DLG_GLOBAL_CHANGE_WARNING = 1;

    private DisplayManager mDisplayManager;

    private CheckBoxPreference mAccelerometer;
    private WarnedListPreference mFontSizePref;
    private CheckBoxPreference mNotificationPulse;

    private final Configuration mCurConfig = new Configuration();
    
    private ListPreference mScreenTimeoutPreference;
    private Preference mScreenSaverPreference;

    private WifiDisplayStatus mWifiDisplayStatus;
    private Preference mWifiDisplayPreference;
    //picture mode:Game
    private static final int PICTURE_MODE_GAME = 4;
    //aspectratio:1:1
    private static final int ASPECTRATIO_1_1 = 5;

    private final RotationPolicy.RotationPolicyListener mRotationPolicyListener =
            new RotationPolicy.RotationPolicyListener() {
        @Override
        public void onChange() {
            updateAccelerometerRotationCheckbox();
        }
    };
	
	private int height =0;
	private int width =0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActivity().setTitle(R.string.picture_settings);
        ContentResolver resolver = getActivity().getContentResolver();

        addPreferencesFromResource(R.xml.display_settings);
        
        //mContext = this;
        registerRGBReceiver();
		mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
		//editor = mSharedPrefs.edit();
		Log.d(TAG, "Imagemode-->Imagemode:1"  );		
		mPdg = new PowerDataGettings(getActivity());
		Log.d(TAG, "Imagemode-->Imagemode:2" );
		editor = mPdg.editor;
		Log.d(TAG, "Imagemode-->Imagemode:3"  );
		
        mImageModePreference = (ListPreference) findPreference(KEY_IMAGE_MODE);
		Log.d(TAG, "Imagemode-->Imagemode:4"  );
		setPreferenceEnable(mImageModePreference);
		Log.d(TAG, "Imagemode-->Imagemode:5"  );
		final int currentImageMode  = getImageMode();
		Log.d(TAG, "Imagemode-->Imagemode:6"  );
		mOldImageMode = currentImageMode;
		
		Log.d(TAG, "Imagemode-->Imagemode:" + currentImageMode);
		/*int currentSource = TvFramework.getInstance().getLiveTvInstance().getCurrentSource();
		Log.d(TAG, "getLiveTvInstance------->>>>currentSource "+currentSource);*/
		int currentSource = 0;
		updateImageModeTitle(currentImageMode);
		setRetailModeFromBootWizard();
        mImageModePreference.setOnPreferenceChangeListener(this);
//		mImageModePreference.setDialogLayoutResource(R.style.HisenseDialog);
//		mImageModePreference.getContext().setTheme(R.style.HisenseDialog);
					
		mAspectratioPreference = (ListPreference) findPreference(KEY_ASPECTRATIO_MODE);
		if(currentSource!=2){
		mAspectratioPreference.setEntryValues(getResources().getStringArray(R.array.aspect_values));
		mAspectratioPreference.setEntries(getResources().getStringArray(R.array.aspect_entries));
		}
		
		final int currentAspectratioMode = getAspectratioMode();
		mOldAspectratioMode = currentAspectratioMode;
		Log.d(TAG, "currentAspectratioMode " + currentAspectratioMode);
		updateaspectratioModeTitle(currentAspectratioMode);
		mAspectratioPreference.setOnPreferenceChangeListener(this);
//		mAspectratioPreference.setDialogThemeResource(R.style.HisenseDialog);
		String secondActivityName = getSecondActivityAtStack(getActivity());
		boolean isOnlyTvPlayer = "com.google.tv.player.PlayerActivity".equals(secondActivityName);
		Log.d(TAG, "isOnlyTvPlayer " + isOnlyTvPlayer);
		if(isOnlyTvPlayer){
			SharedPreferences.Editor editorA = mSharedPrefs.edit();
			editorA.putBoolean(ASPECT_RATIO_ENABLE, true);      
			editorA.commit();
		}
		if(mSharedPrefs.getBoolean(ASPECT_RATIO_ENABLE, true)||isOnlyTvPlayer){
			mAspectratioPreference.setEnabled(true);
		}else{
			mAspectratioPreference.setEnabled(false);
		}
		//brightness
		mBrightnessPreferrence = (Preference)findPreference(KEY_IMAGE_BRIGHTNESS);
		setPreferenceEnable(mBrightnessPreferrence);
		mBrightnessPreferrence.setTitle(getString(R.string.image_brightness).toString() +": " + Wrapper.getWrapperInstance().getBrightNess());
		mBrightnessPreferrence.setOnPreferenceChangeListener(this);
//		mBrightnessPreferrence.setDialogThemeResource(R.style.HisenseDialog);

		//contrast
		mContrastPreferrence = (Preference)findPreference(KEY_IMAGE_CONTRAST);
		setPreferenceEnable(mContrastPreferrence);
		mContrastPreferrence.setTitle(getString(R.string.image_contrast).toString() +": " + Wrapper.getWrapperInstance().getContrast());
		mContrastPreferrence.setOnPreferenceChangeListener(this);
//		mContrastPreferrence.setDialogThemeResource(R.style.HisenseDialog);

		//color
		mColorPreferrence = (Preference)findPreference(KEY_IMAGE_COLOR);
		setPreferenceEnable(mColorPreferrence);
		mColorPreferrence.setTitle(getString(R.string.image_color).toString() +": " + Wrapper.getWrapperInstance().getColor());
		mColorPreferrence.setOnPreferenceChangeListener(this);
//		mColorPreferrence.setDialogThemeResource(R.style.HisenseDialog);
		
		//Tint
		mTintPreferrence = (Preference)findPreference(KEY_IMAGE_TINT);
		setPreferenceEnable(mTintPreferrence);
		mTintPreferrence.setTitle(getString(R.string.image_tint).toString() +": " + Wrapper.getWrapperInstance().getTint());
		mTintPreferrence.setOnPreferenceChangeListener(this);
//		mTintPreferrence.setDialogThemeResource(R.style.HisenseDialog);
		/*if((Wrapper.getWrapperInstance().getCurrentSourceType()
                == TvSourceType.TV_SOURCE_TypeVga.value())||(Wrapper.getWrapperInstance().CurrentSource() == InputSourceType.RGB_INPUT)){
			mTintPreferrence.setEnabled(false);
		}
		else {
			mTintPreferrence.setEnabled(true);
		}*/ 		

		//Sharpness
		mSharpnessPreferrence = (Preference)findPreference(KEY_IMAGE_SHARPNESS);
		setPreferenceEnable(mSharpnessPreferrence);
		mSharpnessPreferrence.setTitle(getString(R.string.image_sharpness).toString() +": " + Wrapper.getWrapperInstance().getSharpness());
		mSharpnessPreferrence.setOnPreferenceChangeListener(this);
//		mSharpnessPreferrence.setDialogThemeResource(R.style.HisenseDialog);

		//Backlight
		mBacklightPreference = (Preference)findPreference(KEY_IMAGE_BACKLIGHT);
		setPreferenceEnable(mBacklightPreference);
		mBacklightPreference.setTitle(getString(R.string.image_backlight).toString() +": " + Wrapper.getWrapperInstance().getBackLight());
		mBacklightPreference.setOnPreferenceChangeListener(this);
//		mBacklightPreference.setDialogThemeResource(R.style.HisenseDialog);

		//colortemperature setting	
		mColortemperaturePreference = (ListPreference) findPreference(KEY_COLORTEMPERATURE_MODE);
		setPreferenceEnable(mColortemperaturePreference);
		final int currentColorTemperateMode = getColortemperatureMode();
		mOldColorTemMode = currentColorTemperateMode;		
		updatecolortemperatureModeTitle(currentColorTemperateMode);
		mColortemperaturePreference.setOnPreferenceChangeListener(this);		

		//dynamic noise reduction	
		mDynamicNoiseReductionPreference = (ListPreference) findPreference(KEY_DYNAMICNOISEREDUCTION_MODE);
		setPreferenceEnable(mDynamicNoiseReductionPreference);
		final int currentDynamicnoisereductionMode = getNoiseReductionMode();
		mOldNoiseMode = currentDynamicnoisereductionMode;		
		updateDynamicNoiseReductionModeTitle(currentDynamicnoisereductionMode);
		mDynamicNoiseReductionPreference.setOnPreferenceChangeListener(this);
//		mDynamicNoiseReductionPreference.setDialogThemeResource(R.style.HisenseDialog);
		NoiseReductionEnable();
		
		//add start by tiandeli	frequence 120
		mFrequence120Preference = (ListPreference) findPreference(KEY_FREQUENCE120_MODE);
		final int currentFrequence120Mode = getFrequence120Mode();
		mOld120HzEffect = currentFrequence120Mode;
		updatefrequence120ModeTitle(currentFrequence120Mode);
		mFrequence120Preference.setOnPreferenceChangeListener(this);
		
		if (!Is120HZ()) {
			getPreferenceScreen().removePreference(mFrequence120Preference);
		}
		
		mScreenVGAAdjust = (PreferenceScreen) findPreference(KEY_SCREEN_ADJUST);

		mImageResetpPreference = (PreferenceScreen) findPreference(KEY_IMAGE_RESET);
		setPreferenceEnable(mImageResetpPreference);
		checkboxOverscan = (CheckBoxPreference) findPreference(KEY_IMAGE_OVERSCAN);
		//modify by libaocheng
		/*if(Wrapper.getWrapperInstance().getCurrentSourceType()
                == TvSourceType.TV_SOURCE_TypeVga.value())
		{
			checkboxOverscan.setEnabled(false);	  
		}*/
		checkboxBacklight= (CheckBoxPreference) findPreference(KEY_DYNAMIC_BACKLIGHT);
		checkboxContrast= (CheckBoxPreference) findPreference(KEY_DYNAMIC_CONTRAST);
		//modify by libaocheng
		/*if(Wrapper.getWrapperInstance().getCurrentSourceType()
                == TvSourceType.TV_SOURCE_TypeVga.value()){
			checkboxContrast.setEnabled(false);
		}
		else {
			checkboxContrast.setEnabled(true);
		}*/ 

		setVGAAdjustItemVisble();
		
        setupDynamicBacklight();
        setupDynamicContrast();		
        setupImageOverscan();	
		getImageModeOldState();
		saveRetailModeValues();

        mAccelerometer = (CheckBoxPreference) findPreference(KEY_ACCELEROMETER);
        mAccelerometer.setPersistent(false);
        if (RotationPolicy.isRotationLockToggleSupported(getActivity())) {
            // If rotation lock is supported, then we do not provide this option in
            // Display settings.  However, is still available in Accessibility settings.
            getPreferenceScreen().removePreference(mAccelerometer);
        }

        mScreenSaverPreference = findPreference(KEY_SCREEN_SAVER);
        if (mScreenSaverPreference != null
                && getResources().getBoolean(
                        com.android.internal.R.bool.config_dreamsSupported) == false) {
            // Enabled for debugging epos
            getPreferenceScreen().removePreference(mScreenSaverPreference);
        }
        //add by libaocheng for hide daydream use hisense for Epos
        getPreferenceScreen().removePreference(mScreenSaverPreference);
        //populatePreferredDeepColors();
        
        mScreenTimeoutPreference = (ListPreference) findPreference(KEY_SCREEN_TIMEOUT);
        final long currentTimeout = Settings.System.getLong(resolver, SCREEN_OFF_TIMEOUT,
                FALLBACK_SCREEN_TIMEOUT_VALUE);
        mScreenTimeoutPreference.setValue(String.valueOf(currentTimeout));
        mScreenTimeoutPreference.setOnPreferenceChangeListener(this);
        disableUnusableTimeouts(mScreenTimeoutPreference);
        updateTimeoutPreferenceDescription(currentTimeout);

        mFontSizePref = (WarnedListPreference) findPreference(KEY_FONT_SIZE);
        mFontSizePref.setOnPreferenceChangeListener(this);
        mFontSizePref.setOnPreferenceClickListener(this);
		//this is add by hisense
		getPreferenceScreen().removePreference(mFontSizePref);
        mNotificationPulse = (CheckBoxPreference) findPreference(KEY_NOTIFICATION_PULSE);
        if (mNotificationPulse != null
                && getResources().getBoolean(
                        com.android.internal.R.bool.config_intrusiveNotificationLed) == false) {
            getPreferenceScreen().removePreference(mNotificationPulse);
        } else {
            try {
                mNotificationPulse.setChecked(Settings.System.getInt(resolver,
                        Settings.System.NOTIFICATION_LIGHT_PULSE) == 1);
                mNotificationPulse.setOnPreferenceChangeListener(this);
            } catch (SettingNotFoundException snfe) {
                Log.e(TAG, Settings.System.NOTIFICATION_LIGHT_PULSE + " not found");
            }
        }

        mDisplayManager = (DisplayManager)getActivity().getSystemService(
                Context.DISPLAY_SERVICE);
        mWifiDisplayStatus = mDisplayManager.getWifiDisplayStatus();
        mWifiDisplayPreference = (Preference)findPreference(KEY_WIFI_DISPLAY);
        if (mWifiDisplayStatus.getFeatureState()
                == WifiDisplayStatus.FEATURE_STATE_UNAVAILABLE) {
            getPreferenceScreen().removePreference(mWifiDisplayPreference);
            mWifiDisplayPreference = null;
        }
        
        set120HzPreferenceEnable(); 
    }

	private void NoiseReductionEnable() {
		/*if (Wrapper.getWrapperInstance().getCurrentSourceType() == TvSourceType.TV_SOURCE_TypeStream
				.value()) {
			mDynamicNoiseReductionPreference.setEnabled(false);
		}else{
			mDynamicNoiseReductionPreference.setEnabled(true);
		}*/
		mDynamicNoiseReductionPreference.setEnabled(true);
	}



    /**
     * this and the followed is add for hisense deep color
     */
    /*private boolean handleSelectPreferredDeepColor(Object newValue) {
        String setting = newValue.toString();
        Log.d(TAG, "handleSelectPreferredDeepColor: " + setting);
        // Native observer will refresh display mode to make deep color change effective
        return mVideoOut.setPreferredDeepColorMode(setting);
    }
    private void populatePreferredDeepColors() {
        ListPreference deepColorPref =
            (ListPreference) findPreference(KEY_DEEP_COLOR_MODE);
        String cur = mVideoOut.getPreferredDeepColorMode();
        Log.d(TAG, "populatePreferredDeepColors, current " + cur);
        if (cur == null) {
            cur = DEEP_COLOR_MODE_8BIT;
            Log.d(TAG, "populatePreferredDeepColors, use '8-bit' by default");
            mVideoOut.setPreferredDeepColorMode(cur);
        }

        deepColorPref.setValue(cur);
        deepColorPref.setOnPreferenceChangeListener(
                new Preference.OnPreferenceChangeListener() {
            public boolean onPreferenceChange(Preference preference,
                    Object newValue) {
                if (newValue.equals(mVideoOut.getPreferredDeepColorMode())) {
                    Log.d(TAG, "no change, ignore");
                    return true;
                }
                return handleSelectPreferredDeepColor(newValue);
            }
        });
    }*/
    private void updateTimeoutPreferenceDescription(long currentTimeout) {
        ListPreference preference = mScreenTimeoutPreference;
        String summary;
        if (currentTimeout < 0) {
            // Unsupported value
            summary = "";
        } else {
            final CharSequence[] entries = preference.getEntries();
            final CharSequence[] values = preference.getEntryValues();
            if (entries == null || entries.length == 0) {
                summary = "";
            } else {
                int best = 0;
                for (int i = 0; i < values.length; i++) {
                    long timeout = Long.parseLong(values[i].toString());
                    if (currentTimeout >= timeout) {
                        best = i;
                    }
                }
                summary = preference.getContext().getString(R.string.screen_timeout_summary,
                        entries[best]);
            }
        }
        preference.setSummary(summary);
    }

    private void disableUnusableTimeouts(ListPreference screenTimeoutPreference) {
        final DevicePolicyManager dpm =
                (DevicePolicyManager) getActivity().getSystemService(
                Context.DEVICE_POLICY_SERVICE);
        final long maxTimeout = dpm != null ? dpm.getMaximumTimeToLock(null) : 0;
        if (maxTimeout == 0) {
            return; // policy not enforced
        }
        final CharSequence[] entries = screenTimeoutPreference.getEntries();
        final CharSequence[] values = screenTimeoutPreference.getEntryValues();
        ArrayList<CharSequence> revisedEntries = new ArrayList<CharSequence>();
        ArrayList<CharSequence> revisedValues = new ArrayList<CharSequence>();
        for (int i = 0; i < values.length; i++) {
            long timeout = Long.parseLong(values[i].toString());
            if (timeout <= maxTimeout) {
                revisedEntries.add(entries[i]);
                revisedValues.add(values[i]);
            }
        }
        if (revisedEntries.size() != entries.length || revisedValues.size() != values.length) {
            screenTimeoutPreference.setEntries(
                    revisedEntries.toArray(new CharSequence[revisedEntries.size()]));
            screenTimeoutPreference.setEntryValues(
                    revisedValues.toArray(new CharSequence[revisedValues.size()]));
            final int userPreference = Integer.parseInt(screenTimeoutPreference.getValue());
            if (userPreference <= maxTimeout) {
                screenTimeoutPreference.setValue(String.valueOf(userPreference));
            } else {
                // There will be no highlighted selection since nothing in the list matches
                // maxTimeout. The user can still select anything less than maxTimeout.
                // TODO: maybe append maxTimeout to the list and mark selected.
            }
        }
        screenTimeoutPreference.setEnabled(revisedEntries.size() > 0);
    }

    int floatToIndex(float val) {
        String[] indices = getResources().getStringArray(R.array.entryvalues_font_size);
        float lastVal = Float.parseFloat(indices[0]);
        for (int i=1; i<indices.length; i++) {
            float thisVal = Float.parseFloat(indices[i]);
            if (val < (lastVal + (thisVal-lastVal)*.5f)) {
                return i-1;
            }
            lastVal = thisVal;
        }
        return indices.length-1;
    }
    
    public void readFontSizePreference(ListPreference pref) {
        try {
            mCurConfig.updateFrom(ActivityManagerNative.getDefault().getConfiguration());
        } catch (RemoteException e) {
            Log.w(TAG, "Unable to retrieve font size");
        }

        // mark the appropriate item in the preferences list
        int index = floatToIndex(mCurConfig.fontScale);
        pref.setValueIndex(index);

        // report the current size in the summary text
        final Resources res = getResources();
        String[] fontSizeNames = res.getStringArray(R.array.entries_font_size);
        pref.setSummary(String.format(res.getString(R.string.summary_font_size),
                fontSizeNames[index]));
    }
    
    @Override
    public void onResume() {
        super.onResume();
		Log.d(TAG, "getImageMode()"+getImageMode()  );

        RotationPolicy.registerRotationPolicyListener(getActivity(),
                mRotationPolicyListener);

        if (mWifiDisplayPreference != null) {
            getActivity().registerReceiver(mReceiver, new IntentFilter(
                    DisplayManager.ACTION_WIFI_DISPLAY_STATUS_CHANGED));
            mWifiDisplayStatus = mDisplayManager.getWifiDisplayStatus();
        }

        updateState();
        
        /*if(Wrapper.getWrapperInstance().getCurrentSourceType()
                == TvSourceType.TV_SOURCE_TypeVga.value()){
			checkboxContrast.setEnabled(false);
		}
		else {
			checkboxContrast.setEnabled(true);
		}*/ 
        
		NoiseReductionEnable();
		set120HzPreferenceEnable();
		
		/*if((Wrapper.getWrapperInstance().getCurrentSourceType()
                == TvSourceType.TV_SOURCE_TypeVga.value())||(Wrapper.getWrapperInstance().CurrentSource() == InputSourceType.RGB_INPUT)){
			mTintPreferrence.setEnabled(false);
			
		}
		else {
			mTintPreferrence.setEnabled(true);
		} 

		if(Wrapper.getWrapperInstance().getCurrentSourceType()
                == TvSourceType.TV_SOURCE_TypeHdmi.value()){
			if(isHdmiVideo())
			{
				if (getImageOverscanValue() == VALUE_IMAGE_OVERSCAN_ON) 
					checkboxOverscan.setChecked(true);
				else 
					checkboxOverscan.setChecked(false);
				checkboxOverscan.setEnabled(true);
				mTintPreferrence.setEnabled(true);
			}
			else
			{
				checkboxOverscan.setChecked(false);
				checkboxOverscan.setEnabled(false);
				mTintPreferrence.setEnabled(false);
			}
		}*/
		updateImageAllTitle();
    }

	
    @Override
    public void onPause() {
        super.onPause();
		Log.d(TAG, "onPause--getImageMode()"+getImageMode()  );
        RotationPolicy.unregisterRotationPolicyListener(getActivity(),
                mRotationPolicyListener);

        if (mWifiDisplayPreference != null) {
            getActivity().unregisterReceiver(mReceiver);
        }
/*		if(!click_ok&&dialog_dismiss){
			setImageMode(mOldImageMode);
			updateImageModeTitle(mOldImageMode);
//			refreshPictureSeekbarData();
			updateImageModeItem();

			getImageModeOldState();
						//save for retailmode
			editor.putInt(RETAILMODE_IMAGEMODE, mOldImageMode);
			editor.commit(); 
						
			Log.d(TAG, click_ok+"----click_ok----");
		}
*/    }
    
    @Override
    public void onDestroy() {
		Log.d(TAG, "onDestroy--getImageMode()"+getImageMode()  );
		if(mReceiver!=null){
			getActivity().unregisterReceiver(mReceiver);
		}
        super.onDestroy();
    }
    
    private boolean isHdmiVideo()
	{
//        Picture picture = TvFramework.getInstance().getPictureInstance();
//        final USDTVInputVideoResolution videoResolution = picture.getVideoInputResolution();
		/*VideoInfoUpdate videoInfo = TvFramework.getInstance().getVideoInfo(
                HisUtils.getTvRemoteService());
        Log.d(TAG, "getTvRemoteService=" + HisUtils.getTvRemoteService());
        if (videoInfo != null) {
            Log.d(TAG, "videoinfo resolution=" + videoInfo.getActiveWidth()
                    + "x" + videoInfo.getActiveHeight());
			width = videoInfo.getActiveWidth();
			height = videoInfo.getActiveHeight();
		
		}
		
		//there is no 576*480 signal
		if(((width == 576)&&(height==480))||
			((width == 720)&&(height==480))||
			((width == 720)&&(height==576))||
			((width == 1280)&&(height==720))||
			((width == 1920)&&(height==1080)))
			return true;
		else*/
			return false;
	}
	private void setPreferenceEnable(Preference preference) {
	Log.d(TAG, "mPdg.getCurrentRetailMode(0)"  );
		if (mPdg.getCurrentRetailMode()) {
		Log.d(TAG, "mPdg.getCurrentRetailMode()"  );
			preference.setEnabled(false);
		}
	}
	private void setRetailModeFromBootWizard() {
		int currentImageMode = 0;
		if (mPdg.getCurrentRetailMode()) {
			currentImageMode  = getImageMode();
			mOldImageMode = currentImageMode;
			Log.d(TAG, "Imagemode-->Imagemode:" + currentImageMode);	
			/*int currentSource = TvFramework.getInstance().getLiveTvInstance().getCurrentSource();
			Log.d(TAG, "getLiveTvInstance------->>>>currentSource "+currentSource);*/

			setImageMode(IMAGE_MODE_VIVID);
			currentImageMode  = getImageMode();
			mOldImageMode = currentImageMode;
			Log.d(TAG, "Imagemode-->Imagemodesettt:" + getImageMode());
		}
		else{
			currentImageMode  = getImageMode();
			mOldImageMode = currentImageMode;
		}
		updateImageModeTitle(currentImageMode);
	}	
	private void saveRetailModeValues() {
		if (mPdg.getCurrentRetailMode() == false) {
			editor.putBoolean(RETAILMODE_HASSAVE, true);
			editor.putInt(RETAILMODE_IMAGEMODE, Wrapper.getWrapperInstance().getPictureMode());
		} 		
		editor.commit(); 
	}
	private void getImageModeOldState() {
		mOldBrightness = Wrapper.getWrapperInstance().getBrightNess();
		mOldContrast= Wrapper.getWrapperInstance().getContrast();
		mOldColor= Wrapper.getWrapperInstance().getColor();
		mOldTint= Wrapper.getWrapperInstance().getTint();
		mOldSharpness= Wrapper.getWrapperInstance().getSharpness();
		mOldBacklight= Wrapper.getWrapperInstance().getBackLight();	
		mOldColortemperature= Wrapper.getWrapperInstance().getColorTemperature();
	}
	private void setVGAAdjustItemVisble(){
		/*if(Wrapper.getWrapperInstance().getCurrentSourceType()!= TvSourceType.TV_SOURCE_TypeVga.value()){
			mScreenVGAAdjust.setEnabled(false);
		}
		else {
			mScreenVGAAdjust.setEnabled(true);
		}*/ 
	}
    private int getAspectratioMode() {
        int aspectratiomode = 0;
		aspectratiomode = Wrapper.getWrapperInstance().getScreenMode();
        return aspectratiomode;
    }

    private void setAspectratioMode(int aspectratiomode) {
		Log.d(TAG, "aspectratiomode:" + aspectratiomode);	
		/*int currentSource = TvFramework.getInstance().getLiveTvInstance().getCurrentSource();
		if(aspectratiomode==4&&currentSource!=2){
			aspectratiomode=5;
		}*/
		Wrapper.getWrapperInstance().setScreenMode(aspectratiomode);
    }

	private void updateaspectratioModeTitle(int value) {
		/*int currentSource = TvFramework.getInstance().getLiveTvInstance().getCurrentSource();
		mAspectratioPreference.setValue((String.valueOf(value)));
		int index = mAspectratioPreference.findIndexOfValue(String.valueOf(value));
		if(index==4&&currentSource!=2){
			index=5;
		}
		if(index != -1)
		{
			mAspectratioPreference.setTitle(getString(R.string.aspectratio).toString() + ": "
					+ this.getResources().getStringArray(R.array.aspectratio_entries)[index]);		
		}*/
    }

	//imageMode
    private int getImageMode() {
        int imagemode = 0;
		imagemode = Wrapper.getWrapperInstance().getPictureMode();
        return imagemode;
    }
    private void setImageMode(int imageMode) {
		Wrapper.getWrapperInstance().setPictureMode(imageMode);
    }

    private void updateImageModeTitle(int value) {
		mImageModePreference.setValue((String.valueOf(value)));
		int index = mImageModePreference.findIndexOfValue(String.valueOf(value));
		Log.d(TAG, "Imagemode-->Imagemode:" + getImageMode());
		Log.d(TAG, "index" + index);
		if(index != -1){
			mImageModePreference.setTitle(getString(R.string.image_mode).toString() + ": "
					+ this.getResources().getStringArray(R.array.image_mode_entries)[index]);
		}
    }
	//ColortemperatureMode
    private int getColortemperatureMode() {
        int colorTemperaturemode = 0;
		colorTemperaturemode = Wrapper.getWrapperInstance().getColorTemperature();
        return colorTemperaturemode;

    }
    private void setColortemperatureMode(int colorTemperature) {
        Wrapper.getWrapperInstance().setColorTemperature(colorTemperature);
    }

	private void updatecolortemperatureModeTitle(int value) {
		mColortemperaturePreference.setValue((String.valueOf(value)));
		int index = mColortemperaturePreference.findIndexOfValue(String.valueOf(value));
		if(index != -1) {
			mColortemperaturePreference.setTitle(getString(R.string.image_colortemperature).toString() + ": "
				+ this.getResources().getStringArray(R.array.colortemperature_entries)[index]);	
		} 
    }

	private int getDynamicContrastValue() {
        int value = Wrapper.getWrapperInstance().getDynamicContrast();
        return value;
    }
    private void setDynamicContrastValue(int value) {
        Wrapper.getWrapperInstance().setDynamicContrast(value);
    }
	

    private int getNoiseReductionMode() {
        int noiseReductionmode = 0;
		noiseReductionmode = Wrapper.getWrapperInstance().getNoiseReduction();
        return noiseReductionmode;

    }
    private void setNoiseReductionValue(int noiseReductio) {
		Wrapper.getWrapperInstance().setNoiseReduction(noiseReductio);
    }
	
	private void updateDynamicNoiseReductionModeTitle(int value) {
		mDynamicNoiseReductionPreference.setValue((String.valueOf(value)));
		int index = mDynamicNoiseReductionPreference.findIndexOfValue(String.valueOf(value));
		if(index != -1) {
			mDynamicNoiseReductionPreference.setTitle(getString(R.string.image_dynamicnoisereduction).toString() + ": "
				+ this.getResources().getStringArray(R.array.dynamicnoisereduction_entries)[index]);		
		} 
    }

	private int getFrequence120Mode() {
		int value = 0;
		value = Wrapper.getWrapperInstance().getSmoothness();
		Log.d(TAG, "getFrequence120Mode-->value:" + value);
		return value;
	}

	private void setFrequence120Mode(int value) {
		Log.d(TAG, "setFrequence120Mode-->value:" + value);
		Wrapper.getWrapperInstance().setSmoothness(value);
	}
    
	private void updatefrequence120ModeTitle(int value) {
		mFrequence120Preference.setValue(String.valueOf(value));
		int index = mFrequence120Preference.findIndexOfValue(String.valueOf(value));
		if (index != -1) {
			mFrequence120Preference.setTitle(getString(R.string.image_120hzeffect_title).toString()
					+ ": "+ this.getResources().getStringArray(R.array.frequence120_entries)[index]);
		}
	}
	
    private int getDynamicBacklightValue() {
        int value = Wrapper.getWrapperInstance().getSmartDimming();
        return value;
    }


    private void setDynamicBacklightValue(int value) {
        Wrapper.getWrapperInstance().setSmartDimming(value);
    }

    private void setupDynamicBacklight() {
        checkboxBacklight.setPersistent(true);
		setPreferenceEnable(checkboxBacklight);
		Log.d(TAG, "getDynamicBacklightValue:" + getDynamicBacklightValue());
		if (getDynamicBacklightValue() == VALUE_DYNAMIC_BACKLIGHT) 
			{
			checkboxBacklight.setChecked(true);
			mBacklightPreference.setEnabled(false);
			}
			
		else{ 		
			checkboxBacklight.setChecked(false);
			mBacklightPreference.setEnabled(true);
			}			
        checkboxBacklight.setOnPreferenceClickListener(
                new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                boolean enabled = checkboxBacklight.isChecked();
				Log.d(TAG, "enabled:" + enabled);
                if (enabled){
                    setDynamicBacklightValue(VALUE_DYNAMIC_BACKLIGHT); 					
					}
				else 
                    {setDynamicBacklightValue(0);
					mBacklightPreference.setEnabled(true);
					}
					
				final int currentImageMode	= getImageMode();
				updateImageModeTitle(currentImageMode);
				refreshPictureSeekbarData();
				updateImageModeItem();				
				
				editor.putBoolean(RETAILMODE_DYNAMICBACKLIGHT, enabled);
				editor.commit(); 
                return true;
            }
        });
	
    }

    private void setupDynamicContrast() {
		
		checkboxContrast.setPersistent(true);
		setPreferenceEnable(checkboxContrast);
		Log.d(TAG, "setupDynamicContrast-->setupDynamicContrast:" + getDynamicContrastValue());
		if (getDynamicContrastValue() == VALUE_DYNAMIC) 
			checkboxContrast.setChecked(true);
		else
			checkboxContrast.setChecked(false);	
        checkboxContrast.setOnPreferenceClickListener(
                new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                boolean enabled = checkboxContrast.isChecked();
				boolean state = false;
				int value = 0;
                if (enabled){
                    setDynamicContrastValue(VALUE_DYNAMIC);
					Log.d(TAG, "setupDynamicContrast-->setupDynamicContrast:" + getDynamicContrastValue());
                }
                else
                    setDynamicContrastValue(VALUE_DYNAMIC_CONTRAST_OFF);
				
				final int currentImageMode	= getImageMode();
				updateImageModeTitle(currentImageMode);
				refreshPictureSeekbarData();
				updateImageModeItem();	
							
				editor.putBoolean(RETAILMODE_DYNAMICCONTRAST, enabled);
				editor.commit(); 
                return true;
            }
        });
    }	

	private int getImageOverscanValue() {
        int value = 0;
		value = Wrapper.getWrapperInstance().getOverscan();
        return value;
    }

    private void setImageOverscanValue(int value) {
        Wrapper.getWrapperInstance().setOverscan(value);
    }

	private int get120EffectValue() {
		int value = 0;
		value = Wrapper.getWrapperInstance().getSmoothMotionEffect();
		return value;
	}

	private void set120EffectValue(int value) {
		Wrapper.getWrapperInstance().setSmoothMotionEffect(value);
		Log.d(TAG, "set120EffectValue---> " + value);
	}
    
    private void setImageReset() {
        Wrapper.getWrapperInstance().resetPictureMode();
		Wrapper.getWrapperInstance().resetAdvancedPictureMode();
		mOldImageMode=getImageMode();
		Log.d(TAG, "setimagereset-->:" + getImageMode());
		Log.d(TAG, "Image mode------->>>>setImageReset ");
    }
	private void updateImageAllTitle() {
	
		int value = getImageMode();
		updateImageModeTitle(value);
		Log.d(TAG, "updateImageAllTitle" + getImageMode());
		
		value = getAspectratioMode();
		updateaspectratioModeTitle(value);
		
		value = getColortemperatureMode();
		updatecolortemperatureModeTitle(value);
		
		value = getNoiseReductionMode();	
		updateDynamicNoiseReductionModeTitle(value);
		
		value = getFrequence120Mode();
		updatefrequence120ModeTitle(value);

		if (getDynamicContrastValue() == VALUE_DYNAMIC)
			checkboxContrast.setChecked(true);
		else
			checkboxContrast.setChecked(false);
		if (getDynamicBacklightValue() == VALUE_DYNAMIC_BACKLIGHT)
			checkboxBacklight.setChecked(true);
		else
			checkboxBacklight.setChecked(false);
		if (getImageOverscanValue() == VALUE_IMAGE_OVERSCAN_ON)
			checkboxOverscan.setChecked(true);
		else 
			checkboxOverscan.setChecked(false);
		refreshPictureSeekbarData();
	}

	private void updateImageModeItem() {
		int value = 0;
		
		value = getColortemperatureMode();
		updatecolortemperatureModeTitle(value);
		
		value = getNoiseReductionMode();
		updateDynamicNoiseReductionModeTitle(value);
		
		if (getDynamicContrastValue() > 0) 
			checkboxContrast.setChecked(true);
		else
			checkboxContrast.setChecked(false);	
		if (getDynamicBacklightValue() > 0)
			checkboxBacklight.setChecked(true);
		else 
			checkboxBacklight.setChecked(false);

	}	
    private void setupImageOverscan() {
        checkboxOverscan.setPersistent(true);
		
        //int value = getImageOverscanValue();
        //if RGB disable Overscan
		if (getImageOverscanValue() == VALUE_IMAGE_OVERSCAN_ON) 
			checkboxOverscan.setChecked(true);
		else 
			checkboxOverscan.setChecked(false);
        checkboxOverscan.setOnPreferenceClickListener(
                new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                boolean enabled = checkboxOverscan.isChecked();
                if (enabled) {
                    setImageOverscanValue(VALUE_IMAGE_OVERSCAN_ON);
                } else {
                    setImageOverscanValue(VALUE_IMAGE_OVERSCAN_OFF);				
                }
                return true;
            }
        });
    }	
 
	private void getItemSelectedListenerInstance() {
        Log.d(TAG, "getItemSelectedListenerInstance-->preference:" + mCurrentPreference);
        if (mItemSelectedListener == null) {
            mItemSelectedListener = new OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
					if (mCurrentPreference == mImageModePreference) {
						setImageMode(Integer.parseInt(getResources().getStringArray(R.array.image_mode_values)[position]));
						Log.d(TAG, "position" + position);
						Log.d(TAG, "Integer.parseInt(getResources().getStringArray(R.array.image_mode_values)[position])" + Integer.parseInt(getResources().getStringArray(R.array.image_mode_values)[position]));
//						Wrapper.getWrapperInstance().setPictureMode(Integer.parseInt(getResources().getStringArray(R.array.image_mode_values)[position]));
					} 
					else if (mCurrentPreference == mAspectratioPreference){
						/*int currentSource = TvFramework.getInstance().getLiveTvInstance().getCurrentSource();
						Log.d(TAG, "currentSource:" + currentSource);
						if(position==4&&currentSource!=2){
							position=5;
						}*/
						setAspectratioMode(Integer.parseInt(getResources().getStringArray(R.array.aspectratio_values)[position]));
						Log.d(TAG, "position" + position);
						Log.d(TAG, "position" + getResources().getStringArray(R.array.aspectratio_values)[position]);
					}
					else if (mCurrentPreference == mDynamicNoiseReductionPreference){
						setNoiseReductionValue(Integer.parseInt(getResources().getStringArray(R.array.dynamicnoisereduction_values)[position]));
					}	
					else if (mCurrentPreference == mColortemperaturePreference){
						setColortemperatureMode(Integer.parseInt(getResources().getStringArray(R.array.colortemperature_values)[position]));
					} else if (mCurrentPreference == mFrequence120Preference) {
						set120EffectValue(Integer.parseInt(getResources().getStringArray(R.array.frequence120_values)[position]));
					}

                }

                @Override
                public void onNothingSelected(AdapterView<?> arg0) {
                    Log.d(TAG, "onNothingSelected-->arg0:" + arg0);
                }
            };
        }
    }	
	private void getItemOnCancelListenerInstance() {
		Log.d(TAG, "getItemOnCancelListenerInstance-->preference:"
				+ mCurrentPreference);
        if (mOnCancelListener == null) {
            mOnCancelListener = new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    // TODO Auto-generated method stub
					if (mCurrentPreference == mImageModePreference) {
					Log.d(TAG, "cancel:" + getImageMode());
					
					Log.d(TAG, "cancel:mOldImageMode" + mOldImageMode);
						//setImageMode(mOldImageMode);
						Wrapper.getWrapperInstance().setPictureMode(mOldImageMode);
					}
					else if (mCurrentPreference == mAspectratioPreference){
						setAspectratioMode(mOldAspectratioMode);
					}
					else if (mCurrentPreference == mDynamicNoiseReductionPreference){
						setNoiseReductionValue(mOldNoiseMode);
					}	
					else if (mCurrentPreference == mColortemperaturePreference){
						setColortemperatureMode(mOldColorTemMode);
					} else if (mCurrentPreference == mFrequence120Preference) {
						setFrequence120Mode(mOld120HzEffect);
					}

                }

            };
		}
		
	}

	private void getItemOnClickListenerInstance() {
		if (mOnClickListener == null) {
            mOnClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) { 
                    // TODO Auto-generated method stub
					if (mCurrentPreference == mImageModePreference) {
					Log.d(TAG, "Imagemode-->onclick:" + getImageMode());
						//setImageMode(mOldImageMode);
						Wrapper.getWrapperInstance().setPictureMode(mOldImageMode);
						mAlertDialog.dismiss();
					}
					else if (mCurrentPreference == mAspectratioPreference){
						setAspectratioMode(mOldAspectratioMode);
						mAlertDialog.dismiss();
					}
					else if (mCurrentPreference == mDynamicNoiseReductionPreference){
						setNoiseReductionValue(mOldNoiseMode);
						mAlertDialog.dismiss();
					}	
					else if (mCurrentPreference == mColortemperaturePreference){
						setColortemperatureMode(mOldColorTemMode);
						mAlertDialog.dismiss();
					} else if (mCurrentPreference == mFrequence120Preference) {
						setFrequence120Mode(mOld120HzEffect);
						mAlertDialog.dismiss();
					}

                }
            };
		}
	}
	
   /**
     *afteer select color temperature mode,if image mode not custom,need restore dynamic noise/
     *dynamic backlight/dynamic contrast
     * 
     */
    private void dealAfterColortemperatureSelected() {		
		int currentImageMode  = getImageMode();
		updateImageModeTitle(currentImageMode);
		refreshPictureSeekbarData();
	}
   /**
     *afteer select color dynamic mode,if image mode not custom,need restore temperature noise/
     *dynamic backlight/dynamic contrast
     * 
     */
    private void dealAfterDynamicnoiseSelected() {
		
		int currentImageMode  = getImageMode();
		updateImageModeTitle(currentImageMode);
		refreshPictureSeekbarData();
	}   
   /**
     *afteer select Image mode,if image mode not custom,need restore temperature noise/
     *dynamic backlight/dynamic contrast/dynamic noise
     * 
     */
    private void dealAfterImagemodeSelected() {
		if(getImageMode() == IMAGE_MODE_CUSTOM) return;
		
		int val = 0;
		val = mPdg.getModeImageCustomDynamic();
		setNoiseReductionValue(val);
		updateDynamicNoiseReductionModeTitle(val);
		val = mPdg.getModeImageCustomColor();
		setColortemperatureMode(val);
		updatecolortemperatureModeTitle(val);			
	}      
   
	
	

    @Override
    public Dialog onCreateDialog(int dialogId) {
        if (dialogId == DLG_GLOBAL_CHANGE_WARNING) {
            return Utils.buildGlobalChangeWarningDialog(getActivity(),
                    R.string.global_font_change_title,
                    new Runnable() {
                        public void run() {
                            mFontSizePref.click();
                        }
                    });
        }
        
        if (dialogId == DIALOG_IMAGE_RESET) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
        //.setIconAttribute(android.R.attr.alertDialogIcon)
        .setTitle(R.string.image_reset)
        .setMessage(R.string.image_reset_message)
        .setPositiveButton(R.string.dlg_ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
			Log.d(TAG, "ok-->Imagereset:" + getImageMode());
                /* User clicked OK so do some stuff */
				setImageReset();	
				updateImageAllTitle();
				Log.d(TAG, "ok-->Imagemode:" + getImageMode());
            }
        })
        .setNegativeButton(R.string.dlg_cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

                /* User clicked Cancel so do some stuff */
            }
        });


        return builder.create();
    }
        return null;
    }

    private void updateState() {
        updateAccelerometerRotationCheckbox();
        readFontSizePreference(mFontSizePref);
        updateScreenSaverSummary();
        updateWifiDisplaySummary();
    }

    private void updateScreenSaverSummary() {
        if (mScreenSaverPreference != null) {
            mScreenSaverPreference.setSummary(
                    DreamSettings.getSummaryTextWithDreamName(getActivity()));
        }
    }

    private void updateWifiDisplaySummary() {
        if (mWifiDisplayPreference != null) {
            switch (mWifiDisplayStatus.getFeatureState()) {
                case WifiDisplayStatus.FEATURE_STATE_OFF:
                    mWifiDisplayPreference.setSummary(R.string.wifi_display_summary_off);
                    break;
                case WifiDisplayStatus.FEATURE_STATE_ON:
                    mWifiDisplayPreference.setSummary(R.string.wifi_display_summary_on);
                    break;
                case WifiDisplayStatus.FEATURE_STATE_DISABLED:
                default:
                    mWifiDisplayPreference.setSummary(R.string.wifi_display_summary_disabled);
                    break;
            }
        }
    }

    private void updateAccelerometerRotationCheckbox() {
        if (getActivity() == null) return;

        mAccelerometer.setChecked(!RotationPolicy.isRotationLocked(getActivity()));
    }

    public void writeFontSizePreference(Object objValue) {
        try {
            mCurConfig.fontScale = Float.parseFloat(objValue.toString());
            ActivityManagerNative.getDefault().updatePersistentConfiguration(mCurConfig);
        } catch (RemoteException e) {
            Log.w(TAG, "Unable to save font size");
        }
    }

    @Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
        if (preference == mAccelerometer) {
            RotationPolicy.setRotationLockForAccessibility(
                    getActivity(), !mAccelerometer.isChecked());
        } else if (preference == mNotificationPulse) {
            boolean value = mNotificationPulse.isChecked();
            Settings.System.putInt(getContentResolver(), Settings.System.NOTIFICATION_LIGHT_PULSE,
                    value ? 1 : 0);
            return true;
        }
        
        if (preference == mImageResetpPreference) {
            showDialog(DIALOG_IMAGE_RESET);
        }
        
		if ((preference != mImageModePreference)
				&& (preference != mAspectratioPreference)
				&& (preference != mDynamicNoiseReductionPreference)
				&& (preference != mColortemperaturePreference)
				&& (preference != mFrequence120Preference)){
			return false;			
		}
		
		mCurrentPreference = preference;
        mAlertDialog = (AlertDialog)((ListPreference)mCurrentPreference).getDialog();
        getItemSelectedListenerInstance();
        getItemOnCancelListenerInstance();
        getItemOnClickListenerInstance();
//		getItemOnKeyListenerInstance();
        if(preference != null){
        	mAlertDialog.getListView().setOnItemSelectedListener(mItemSelectedListener);
        	mAlertDialog.setOnCancelListener(mOnCancelListener);
        	mAlertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener(mOnClickListener);
        }
        return super.onPreferenceTreeClick(preferenceScreen, preference);
    }

    public boolean onPreferenceChange(Preference preference, Object objValue) {
	Log.d(TAG, "Imagemode-->change:" + getImageMode());
        final String key = preference.getKey();
        if (KEY_SCREEN_TIMEOUT.equals(key)) {
            int value = Integer.parseInt((String) objValue);
            try {
                Settings.System.putInt(getContentResolver(), SCREEN_OFF_TIMEOUT, value);
                updateTimeoutPreferenceDescription(value);
            } catch (NumberFormatException e) {
                Log.e(TAG, "could not persist screen timeout setting", e);
            }
        }
        if (KEY_FONT_SIZE.equals(key)) {
            writeFontSizePreference(objValue);
        }
        
        if (KEY_IMAGE_MODE.equals(key)) {
           final int value = Integer.parseInt((String) objValue);
		   Log.d(TAG, "Imagemode-->value:" + value);
            try {
			if(value==6)
			{
				checkboxBacklight.setChecked(true);
				setImageMode(value);
				mOldImageMode= value;
				updateImageModeTitle(value);
				refreshPictureSeekbarData();
				updateImageModeItem();
				getImageModeOldState();
				//save for retailmode
				editor.putInt(RETAILMODE_IMAGEMODE, value);
				editor.commit(); 
				
			}
			else
			{
				AlertDialog.Builder builder = new Builder(getActivity());		
				builder.setTitle(R.string.picture_mode);
				builder.setMessage(R.string.picture_mode_message);
				builder.setCancelable(false);
/*				builder.setOnDismissListener(new OnDismissListener() {
					
					@Override
					public void onDismiss(DialogInterface arg0) {
						if(!click_ok){
						setImageMode(mOldImageMode);
						updateImageModeTitle(mOldImageMode);
						refreshPictureSeekbarData();
						updateImageModeItem();

						getImageModeOldState();
						//save for retailmode
						editor.putInt(RETAILMODE_IMAGEMODE, mOldImageMode);
						editor.commit(); 
						
						Log.d(TAG, click_ok+"----click_ok----");
						}
						click_ok=false;
						Log.d(TAG, click_ok+"----onDismiss----");
					}

				});				
*/				builder.setPositiveButton(android.R.string.ok, new OnClickListener(){				
					public void onClick(DialogInterface dialog, int which) {
					Log.d(TAG, "----OKOK-value---"+value);
					if(value==0||value==4)
					{
						checkboxBacklight.setChecked(false);
					}else{
						checkboxBacklight.setChecked(true);
					}
						Log.d(TAG, "----OKOKOKOKOK----");
						click_ok=true;
						setImageMode(value);
						mOldImageMode= value;
						updateImageModeTitle(value);
						refreshPictureSeekbarData();
						updateImageModeItem();

						getImageModeOldState();
						
						set120HzPreferenceEnable();						
                        int tempFrequence120Mode = getFrequence120Mode();
                        updatefrequence120ModeTitle(tempFrequence120Mode);
						
						//save for retailmode
						editor.putInt(RETAILMODE_IMAGEMODE, value);
						editor.commit(); 
						dialog.dismiss();
					}});
				builder.setNegativeButton(android.R.string.cancel, new OnClickListener(){				
					public void onClick(DialogInterface dialog, int which) {
						setImageMode(mOldImageMode);
						updateImageModeTitle(mOldImageMode);
						refreshPictureSeekbarData();
						updateImageModeItem();

						getImageModeOldState();
						//save for retailmode
						editor.putInt(RETAILMODE_IMAGEMODE, mOldImageMode);
						editor.commit(); 
						dialog.dismiss();
						Log.d(TAG, mOldImageMode+"----mOldImageMode----");
				
					}});
				
				localDialog=builder.create();			
				
				localDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
				localDialog.show();
				dialog_dismiss=true;
				Log.d(TAG, dialog_dismiss+"----dialog_dismiss----");
				return false;
			}
            } catch (NumberFormatException e) {
                Log.e(TAG, "could not persist screen timeout setting", e);
            }
        }
       else if (KEY_ASPECTRATIO_MODE.equals(key)) {
            int value = Integer.parseInt((String) objValue);
			Log.d(TAG, "----value----"+value);
            try {
				setAspectratioMode(value);
				mOldAspectratioMode = value;
				updateaspectratioModeTitle(value);	
				set120HzPreferenceEnable();
            } catch (NumberFormatException e) {
                Log.e(TAG, "could not persist screen timeout setting", e);
            }
        }		
		//brightness 
        else if (KEY_IMAGE_BRIGHTNESS.equals(key)) {
            int value = (Integer) objValue;
            try {
					//mBrightnessPreferrence.setTitle(getString(R.string.image_brightness).toString() +" : " + value);
					if (mOldBrightness == value && mOldImageMode != Wrapper.getWrapperInstance().getPictureMode()) {
						mOldImageMode = Wrapper.getWrapperInstance().getPictureMode();
						setImageMode(mOldImageMode);
					}
					final int currentImageMode	= getImageMode();
					updateImageModeTitle(currentImageMode);
					refreshPictureSeekbarData();
					updateImageModeItem();					

            } catch (NumberFormatException e) {
                Log.e(TAG, " ", e);
            }
        }
		//contrast 
        else if (KEY_IMAGE_CONTRAST.equals(key)) {
            int value = (Integer) objValue;
            try {
					//mContrastPreferrence.setTitle(getString(R.string.image_contrast).toString() +" : " + value);
					if (mOldContrast == value && mOldImageMode != Wrapper.getWrapperInstance().getPictureMode()) {
					mOldImageMode=Wrapper.getWrapperInstance().getPictureMode();
					Log.d(TAG, "mOldImageMode***********: "+mOldImageMode);
						setImageMode(mOldImageMode);
					}
					Log.d(TAG, "getImageMode***********: "+getImageMode());					
					final int currentImageMode  = getImageMode();
					updateImageModeTitle(currentImageMode);
					refreshPictureSeekbarData();
					updateImageModeItem();						
            } catch (NumberFormatException e) {
                Log.e(TAG, " ", e);
            }
        }		
		//color
        else if (KEY_IMAGE_COLOR.equals(key)) {
            int value = (Integer) objValue;
            try {
					//mColorPreferrence.setTitle(getString(R.string.image_color).toString() +" : " + value);
					if (mOldColor == value && mOldImageMode != Wrapper.getWrapperInstance().getPictureMode()) {
						mOldImageMode = Wrapper.getWrapperInstance().getPictureMode();
						setImageMode(mOldImageMode);
					}						
					final int currentImageMode  = getImageMode();
					updateImageModeTitle(currentImageMode);
					refreshPictureSeekbarData();
					updateImageModeItem();						
            } catch (NumberFormatException e) {
                Log.e(TAG, " ", e);
            }
        }	
		//tint
        else if (KEY_IMAGE_TINT.equals(key)) {
            int value = (Integer) objValue;
            try {
					//mTintPreferrence.setTitle(getString(R.string.image_tint).toString() +" : " + value);
					if (mOldTint == value && mOldImageMode != Wrapper.getWrapperInstance().getPictureMode()) {
						mOldImageMode = Wrapper.getWrapperInstance().getPictureMode();
						setImageMode(mOldImageMode);
					}						
					final int currentImageMode  = getImageMode();
					updateImageModeTitle(currentImageMode);
					refreshPictureSeekbarData();
					updateImageModeItem();						
            } catch (NumberFormatException e) {
                Log.e(TAG, " ", e);
            }
        }
		//sharpness
        else if (KEY_IMAGE_SHARPNESS.equals(key)) {
            int value = (Integer) objValue;
            try {
					//mSharpnessPreferrence.setTitle(getString(R.string.image_sharpness).toString() +" : " + value);
					if (mOldSharpness == value && mOldImageMode != Wrapper.getWrapperInstance().getPictureMode()) {
						mOldImageMode = Wrapper.getWrapperInstance().getPictureMode();
						setImageMode(mOldImageMode);
					}						
					final int currentImageMode  = getImageMode();
					updateImageModeTitle(currentImageMode);
					refreshPictureSeekbarData();
					updateImageModeItem();						
            } catch (NumberFormatException e) {
                Log.e(TAG, " ", e);
            }
        }
		//Backlight
        else if (KEY_IMAGE_BACKLIGHT.equals(key)) {
            int value = (Integer) objValue;
            try {
					//mBacklightPreference.setTitle(getString(R.string.image_backlight).toString() +" : " + value);
					if (mOldBacklight == value && mOldImageMode != Wrapper.getWrapperInstance().getPictureMode()) {
						mOldImageMode = Wrapper.getWrapperInstance().getPictureMode();
						setImageMode(mOldImageMode);
					}						
					final int currentImageMode  = getImageMode();
					updateImageModeTitle(currentImageMode);
					refreshPictureSeekbarData();
					updateImageModeItem();						
            } catch (NumberFormatException e) {
                Log.e(TAG, " ", e);
            }
        }	

        else if (KEY_COLORTEMPERATURE_MODE.equals(key)) {
            int value = Integer.parseInt((String) objValue);
            try {
				setColortemperatureMode(value);
				mOldColorTemMode = value;
				//updatecolortemperatureModeTitle(value);
				dealAfterColortemperatureSelected();	
				updateImageModeItem();
				editor.putInt(CUSTOM_MODE_COLORTEMPERETURE,value);
				editor.commit();				

            } catch (NumberFormatException e) {
                Log.e(TAG, "could not persist screen timeout setting", e);
            }
        }
	
        else if (KEY_DYNAMICNOISEREDUCTION_MODE.equals(key)) {
            int value = Integer.parseInt((String) objValue);
            try {
				setNoiseReductionValue(value);
				mOldNoiseMode = value;
				//updateDynamicNoiseReductionModeTitle(value);
				dealAfterDynamicnoiseSelected();
				updateImageModeItem();
				editor.putInt(CUSTOM_MODE_DYNAMICNOISE,value);
				editor.commit();

            } catch (NumberFormatException e) {
                Log.e(TAG, "could not persist screen timeout setting", e);
            }
		} else if (KEY_FREQUENCE120_MODE.equals(key)) {
			int value = Integer.parseInt((String) objValue);
			try {
				setFrequence120Mode(value);
				mOld120HzEffect = value;
				updatefrequence120ModeTitle(value);
			} catch (NumberFormatException e) {
				Log.e(TAG, "could not persist screen timeout setting", e);
			}
		}
        return true;
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(DisplayManager.ACTION_WIFI_DISPLAY_STATUS_CHANGED)) {
                mWifiDisplayStatus = (WifiDisplayStatus)intent.getParcelableExtra(
                        DisplayManager.EXTRA_WIFI_DISPLAY_STATUS);
                updateWifiDisplaySummary();
            }
            
            if(intent.getAction().equalsIgnoreCase(EVENTS_CHANGE)){
				/*if(intent.getIntExtra("Events", -1) == Events.SCM_VIDEO_RESOLUTION_CHANGE.ordinal()){
		            Log.d(TAG,"SCM_VIDEO_RESOLUTION_CHANGE enter:");
		            if(isHdmiVideo()){
		            	checkboxOverscan.setEnabled(true);
						mTintPreferrence.setEnabled(true);
	            	}else{
	            		checkboxOverscan.setEnabled(false);
						mTintPreferrence.setEnabled(false);
	            	}
				}*/
			}
        }        
        
    };

    private void refreshPictureSeekbarData(){
	Log.d(TAG, "Imagemode-->refresh:" + getImageMode());
		mBacklightPreference.setTitle(getString(R.string.image_backlight).toString() +": "
		+ Wrapper.getWrapperInstance().getBackLight());
		mBrightnessPreferrence.setTitle(getString(R.string.image_brightness).toString() +": "
		+ Wrapper.getWrapperInstance().getBrightNess());
		mContrastPreferrence.setTitle(getString(R.string.image_contrast).toString() +": "
		+ Wrapper.getWrapperInstance().getContrast());
		mColorPreferrence.setTitle(getString(R.string.image_color).toString() +": " 
		+ Wrapper.getWrapperInstance().getColor());
		mTintPreferrence.setTitle(getString(R.string.image_tint).toString() +": " 
		+ Wrapper.getWrapperInstance().getTint());
		mSharpnessPreferrence.setTitle(getString(R.string.image_sharpness).toString() +": " 
		+ Wrapper.getWrapperInstance().getSharpness());
		
		boolean enabled = checkboxBacklight.isChecked();
				Log.d(TAG, "enabled%%%%:" + enabled);
                if (enabled){                    
					mBacklightPreference.setEnabled(false);
					}
				else                   
					mBacklightPreference.setEnabled(true);
					
	}
    
    private void registerRGBReceiver(){
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(EVENTS_CHANGE);
		getActivity().registerReceiver(mReceiver,intentFilter);
		Log.d(TAG, "RGBregisterReceiver");
	}
/*	private void registerReceiver(BroadcastReceiver mReceiver2,
			IntentFilter intentFilter) {
			registerReceiver(mReceiver2,intentFilter);
				
	}
*/
	private String getSecondActivityAtStack(final Context context){
		
		Log.d(TAG, "getSecondActivityAtStack()");
		String className = "";
		try {
			ActivityManager am = (ActivityManager) context.getSystemService(Activity.ACTIVITY_SERVICE);
			
			/*
			 * getRunningTasks(maxNum)->Return a list of the tasks that are
			 * currently running, with the most recent being first and older ones
			 * after in order.Here maxNum specifies the maximum number of entries to
			 * return in the list. The actual number returned may be smaller,
			 * depending on how many tasks the user has started. As we passed 1 to
			 * getRunningTasks() it will return only 1 task which is most recent
			 * task i.e. currently running task.
			 */
			List<RunningTaskInfo> list = am.getRunningTasks(2);
			if(list != null && list.size() > 0){
				className = list.get(1).topActivity.getClassName(); 			   
			}else{
				Log.e(TAG, "task list is empty");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, " Exception occured " + e);
		}
		return className;
	}
	private boolean Is120HZ() {
		int panelIndexNumFromSystem = readDatFile();
		if ((panelIndexNumFromSystem >= 1) && (panelIndexNumFromSystem <= 8)) {
			Log.i(TAG, "******Is120HZ true----->");
			return true;
		} else {
			Log.i(TAG, "******Is120HZ false----->");
			return false;
		}
	}


	private int readDatFile() {
        int panelIndexNum = 1;
        String tempString = 1 + "";
        String fileName = "/factory_setting/model_index.dat";

        Log.i(TAG, "******file name=" + fileName);
        File file = new File(fileName);
        if (!file.exists()) {
            return 1;
        }
        if (!file.isFile()) {
            return 1;
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));

            if ((tempString = reader.readLine()) != null) {
                Log.i(TAG, "******file content =" + tempString);
                panelIndexNum = Integer.parseInt(tempString);
                Log.i(TAG, "******panel index =" + panelIndexNum);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (NumberFormatException e) {
            Log.d(TAG, "****** NumberFormatException + " + tempString);
        } catch (Exception e){
            Log.d(TAG, "****** Exception + " + e);
        } finally {
            try {
                reader.close();
            } catch (IOException e1) {

            }
        }
        return panelIndexNum;
    }
	
    private void set120HzPreferenceEnable() {
		/*if ((getImageMode() == PICTURE_MODE_GAME)
				|| (getAspectratioMode() == ASPECTRATIO_1_1)
				|| (Wrapper.getWrapperInstance().getCurrentSourceType() == TvSourceType.TV_SOURCE_TypeStream
						.value())) {
            mFrequence120Preference.setEnabled(false);
        } else {
            mFrequence120Preference.setEnabled(true);
        }*/
    }
    
    @Override
    public boolean onPreferenceClick(Preference preference) {
        if (preference == mFontSizePref) {
            if (Utils.hasMultipleUsers(getActivity())) {
                showDialog(DLG_GLOBAL_CHANGE_WARNING);
                return true;
            } else {
                mFontSizePref.click();
            }
        }
        return false;
    }
}
